package com.elbis.business.manager;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.elbis.business.entity.Gamer;
import com.elbis.business.entity.messages.Notification;
import com.elbis.util.HibernateUtil;

public class NotificationManager implements EntityManager<Notification> {

	private static final Logger logger = Logger
			.getLogger(NotificationManager.class);

	@Override
	public Long save(Notification entity) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		Long id = null;
		try {
			trx = session.beginTransaction();
			id = (Long) session.save(entity);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return id;
	}

	@Override
	public void delete(Notification entity) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.delete(entity);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}

	}

	@Override
	public void update(Notification entity) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.update(entity);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Notification> getNotificationsOwnedBy(Gamer gamer) {
		Session session = HibernateUtil.getSession();
		List<Notification> result = null;
		try {
			result = session.createCriteria(Notification.class)
					.add(Restrictions.and(Restrictions.eq("owner", gamer)))
					.list();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return result;
	}

}
